const bmpUtil = require('bitmap');
const app = getApp()

let tianBmp;
let tianHelper = require('TianHelper');
const { achieveOid } = require('./main');
let tianAndWordTimer;
let oneWordInfo;
let currWordStrokeIdx;
let wordACanvas;
let aCanvasSide = 43;
let aBishunCanvasSide = 43;
let fontSize = aCanvasSide*0.03;
let targetPage;
let prepareTianDetail = new Map();
let prepareTianOgg = new Map();
let tianWordInfo = [];
let tianWidth = (wx.getSystemInfoSync().windowWidth*0.97*0.816*0.146);
let prepareWordMappingTian = new Map();
let wordMappingTian = {};
let lastDrawCanvasId = '';
let testHandwrite = new Set();
let promptRedSlashTmpPath = "";//提示圈圈
let promptRedOKTmpPath = "";
let promptCameraOrTmpPath = "";//拍照
let promptTempCommentPath = "";

let pageThis = null;
let isTestCourse = false;//是否测试 
let isAdustPointAlready = false;

class Point2d{
  constructor(xp,yp,xorig,yorig){
      this.x = xp;
      this.y = yp;
      this.xorig = xorig;
      this.yorig = yorig;
  }


};

class StrokesStore
{
  constructor() {
      this.beginP = new Point2d(-1,-1);
      this.penWidth = -1;
  }
}

function getTheComment(frontPrecent, handPrecent, tp, miaoMuIdx, canvasName,isForceScore)
{
  var scoreHand = frontPrecent;
  if(!isForceScore){
    scoreHand += handPrecent;
  }

  var picName = "wrong";

  if (scoreHand > 90)
  {
      scoreHand = 90;
  }

  scoreHand = parseInt(scoreHand);
  var scoreTxt = scoreHand + " 分";

  if (frontPrecent > 45 &&
     handPrecent > 45
  )
  {
    scoreTxt += "，写的真好，满分";
    picName = "right";

  }


  if (frontPrecent < 45 &&
       handPrecent < 45
  )
  {
      if (frontPrecent > 30 &&
          handPrecent > 30
      )
      {
        picName = "right";
      }
      else
      {
          scoreTxt += "，还需多多努力呀";
      }

      if(frontPrecent < 25 ||
         handPrecent < 25  
      ){
          if(scoreHand < 65){
              picName = "wrong";
          }
      }
  }

  if (frontPrecent < 30)
  {
    scoreTxt += "，漏红多" ;
  }

  if (handPrecent < 30)
  {
    scoreTxt += "，笔画过于潦草。";
  }

  if(scoreHand > 60){
    picName = "right";
  }else{
    picName = "wrong";
  }

  var picX = tianWidth*0.7;
  var picY = tianWidth*0.7;
  var picSizeX = tianWidth*0.3;
  var picSizeY = tianWidth*0.3;

  var tianMu1Canvas = wx.createCanvasContext(canvasName); 

  tianMu1Canvas.drawImage("/images/fontData/"+picName+".png",picX,picY, picSizeX, picSizeY);
  
  if(isForceScore){
    scoreHand = "笔画错";
  }else{
    scoreHand += "分";
  }

  tianMu1Canvas.setFontSize(10);
  tianMu1Canvas.setFillStyle("#FF0000");
  tianMu1Canvas.fillText(scoreHand,2,10,aCanvasSide);
  tianMu1Canvas.draw(true);

  tp.setData({ word_comment: scoreTxt});
  console.log(scoreTxt);
}
function combineAndScore(bitmapManual=Set,miaoMuIdx=Number, tp,canvasName=String,isForceScore)
{
    var canvasKey;

    if(miaoMuIdx >= 0){
        canvasKey = "tian-bihua-show-tpl-7-"+miaoMuIdx
    }else{
        canvasKey = _getTplNameByWordListCanvasId(canvasName);
    }

    if(miaoMuIdx >= 0){
      _drawOneTplById(canvasKey, miaoMuIdx, false);
    }else{
      makeOneWordListByCanvasId(canvasName);
    }

    //console.log("combineAndScore:miaoMuIdx="+miaoMuIdx+"\t预先清除判别区="+canvasName+"\t取模板区域="+canvasKey);
    wx.canvasGetImageData({
          canvasId: canvasKey,
          x: 0,
          y: 0,
          width: aCanvasSide,
          height: aCanvasSide,
          success(res) {
            var inMatchPoint = 0;//匹配点数
            var inFontPoint = 0;//字体一共多少点
            var handMatchPoint = 0;//手写的匹配率
            
            var xxc  = wx.createCanvasContext(canvasKey);
            xxc.setLineWidth(fontSize*2);
            xxc.setFillStyle("blue");// 

            for (var x = 0; x < aCanvasSide; x++)
            {
                for (var y = 0; y < aCanvasSide; y++)
                {
                    var isHandDraw = bitmapManual.has(serializeKeyByOrigKey(x,y));//显示的田格字
                                  
                    var handIdxR = 4*(y*aCanvasSide+x) + 0;//4 * x * tianWordInfo[miaoMuIdx].width + y + 0;
                    var handIdxG = 4*(y*aCanvasSide+x) + 1;//4 * x * tianWordInfo[miaoMuIdx].width + y + 1;
                    var handIdxB = 4*(y*aCanvasSide+x) + 2;//4 * x * tianWordInfo[miaoMuIdx].width + y + 2;
                    var handIdxA = 4*(y*aCanvasSide+x) + 3;//4 * x * tianWordInfo[miaoMuIdx].width + y + 3;

                     var disPicC = [];//手写的 canvas
                     disPicC[0] = 255-res.data[handIdxR];
                     disPicC[1] = 255-res.data[handIdxG];
                     disPicC[2] = 255-res.data[handIdxB];

                    if ((disPicC[0] + disPicC[1] + disPicC[2]) < 765 &&
                        isHandDraw
                     )
                    {
                        inMatchPoint++;
                    }

                    if (isHandDraw)
                    {
                      handMatchPoint++;
                      xxc.fillRect(x, y, fontSize*2, fontSize*2) ;

                    }

                    //黑 0， 白 255
                    if ((disPicC[0] + disPicC[1] + disPicC[2]) < 765
                    ){
                      inFontPoint++;
                   }
                }
            }

            xxc.draw(true);

            var perMatFont = 0;
            if (inFontPoint > 0)
            {
                perMatFont = (inMatchPoint / parseFloat(inFontPoint)) * 100;
            }
            perMatFont = perMatFont.toFixed(2);//math.round(perMatFont, 2);

            var handMatFont = 0;
            if (handMatchPoint > 0)
            {
                handMatFont = (inMatchPoint / parseFloat(handMatchPoint)) * 100;
            }
            handMatFont = handMatFont.toFixed(2);//math.round(handMatFont, 2);

            var frontPercent = parseFloat(perMatFont);
            var handPercent = parseFloat(handMatFont);

            console.log("font matching:"+ perMatFont + "%");//红模匹配
            console.log("hand matching:" + handMatFont + "%",);//手写匹配
            getTheComment(frontPercent, handPercent,tp, miaoMuIdx,canvasName,isForceScore);
            
            return ;
          },
          fail:function(e){
            console.log("fail");

          } 
    });
}


function serializeKeyByOrigKey(xorig=Number,yorig=Number)
{
  return Math.ceil(xorig)+','+Math.ceil(yorig);
}

function getHandWrite(oneWordPos, tp, needScore, canvasName)
{
            if (oneWordPos.length == 0 ||
                canvasName.length == 0
            )
            {
                return ;
            }

            let isForceScore = false;
            if(arguments.length == 5){
              isForceScore = arguments[4];
            }

            var beginX = app.globalData.clientWidth;
            var beginY = app.globalData.clientHeight;
           
            var finishX = 0;
            var finishY = 0;

            for(var i=0 ;i<oneWordPos.length;i++)
            {
                var oneS = oneWordPos[i];
                for(var j=0;j< oneS.length;j++)
                {
                    var curP = oneS[j];

                    var curX = curP.beginP.x;
                    var curY = curP.beginP.y;

                    if (beginX > curX)
                    {
                        beginX = curX;
                    }

                    if (beginY > curY)
                    {
                        beginY = curY;
                    }

                    if (finishX < curX)
                    {
                        finishX = curX;
                    }

                    if (finishY < curY)
                    {
                        finishY = curY;
                    }
                }
            }
            
            var wordWidth = finishX - beginX;
            var wordHeight = finishY - beginY;

            let miaoMuIdx = wordMappingTian.getWordIdByMappingId(canvasName);

            var myWordInfo;
            if(miaoMuIdx >= 0){
              myWordInfo = tianWordInfo[miaoMuIdx];
            }else{
              var oneWord = wordMappingTian.getOneWordByMappingId(canvasName);
              myWordInfo = prepareTianDetail.get(oneWord);
            }
            
             //计算比率
             //伸缩比例
             var fontMatWidth = myWordInfo.fontWidth;
             var fontMatHeight = myWordInfo.fontHeight;

            var scaleRatioWidth = parseFloat(fontMatWidth / wordWidth);
            var scaleRatioHeight = parseFloat(fontMatHeight / wordHeight);

            //console.log("wordWidth("+wordWidth+")*scaleRatioWidth("+scaleRatioWidth+")="+wordWidth*scaleRatioWidth);
   
            var disPic = wx.createCanvasContext(canvasName);
            if(wordMappingTian.isNeedDraw(canvasName)){
                if(miaoMuIdx >=0){
                  _drawNotPaintOneTplById(disPic,myWordInfo.wordInfoDesc);
                }else{
                  _drawNotPaintOneTplById(disPic, myWordInfo);
                }
            }else{
                disPic.clearRect(0,0,tianWidth,tianWidth);
            }

            disPic.setLineWidth(0.8);
            disPic.setLineJoin('round');
            disPic.setFillStyle('rgba(0,0,0,0.4)');
            
            var offsetLeft = (tianWidth - aCanvasSide)/2+2;

            var bitmapManual = new Set();//因为老爷酱，手工组织 bitmap。家门の不幸，是本穷の错咩。
            for(var i=0;i< oneWordPos.length;i++)
            {
                var oneS = oneWordPos[i];
                
                var oneX = (oneS[0].beginP.x - beginX)*scaleRatioWidth + offsetLeft+2;
                var oneY = (oneS[0].beginP.y - beginY)*scaleRatioHeight + offsetLeft;

                disPic.beginPath();
                disPic.moveTo(oneX,oneY);//
                //log += "beginPath()\nmoveTo("+oneS[0].beginP.x+","+oneS[0].beginP.y+")\n";

                for(var j=0;j< oneS.length;j++)
                {
                    var curP = oneS[j];

                    var absX = curP.beginP.x-beginX;
                    var absY = curP.beginP.y-beginY;

                    //1.4189 是宽高补偿
                    var curX = absX*scaleRatioWidth + offsetLeft+2;// * paperWidth) - beginX;
                    var curY = (absY*scaleRatioHeight + offsetLeft);// * paperHeight) - beginY;
                    
                    var justX = absX*scaleRatioWidth;
                    var justY = absY*scaleRatioHeight;

                    bitmapManual.add(serializeKeyByOrigKey(justX,justY));

                    disPic.lineTo(curX, curY);
                }
                disPic.stroke();
            }

            disPic.draw(true,
              function(res){
                console.log("disPic.draw(true");
                console.log(res);
                if(needScore &&
                  !tp.data.isShareZone
                ){
                  combineAndScore(bitmapManual,miaoMuIdx,tp,canvasName, isForceScore);
                }
              }
            );
}


function drawPhraseAndWord(targetPage) {
  var pageWordsList = wordMappingTian.wordPhraseList;
  //拼音的宽高
  var phrasePinyinWidth = wx.getSystemInfoSync().windowWidth*0.97*0.153;
  var phrasePinyinHeight = wx.getSystemInfoSync().windowHeight*0.434*0.287*0.301;

  var isUseNetRequest = false;
  if(arguments.length>=2){
    isUseNetRequest = true;
  }

  //console.log("phrasePinyinWidth="+phrasePinyinWidth+"\tphrasePinyinHeight="+phrasePinyinHeight);

  //描红的宽高
  var phraseWordSize = wx.getSystemInfoSync().windowWidth*0.97*0.153;

  
  var myWordInfo = '';
  var keyPrefix = "tian-bihua-show-";
  if(typeof lineIdx != "undefined"){
    //tian-bihua-show-stepbystep-{{index}}-{{bihuaItem.idx}}
    keyPrefix = 'tian-bihua-show-tpl-'+lineIdx+'-';
  }

  for(var i=0;i<pageWordsList.length;i++){
      var oneWord = pageWordsList[i].substr(0,1);
      var twoWord = pageWordsList[i].substr(1,1);

      //资料信息
      var oneWordInfo;// = require('../images/fontData/' + oneWord + '.base');
      var twoWordInfo;// = require('../images/fontData/' + twoWord + '.base');

      if(isUseNetRequest){
        oneWordInfo = prepareTianDetail.get(oneWord);
        twoWordInfo = prepareTianDetail.get(twoWord);
      }else{
          oneWordInfo = require('../images/fontData/' + oneWord + '.base');
          twoWordInfo = require('../images/fontData/' + twoWord + '.base');
      }

      //先写字
      var oneWordK_A1 = "cizu_word_"+i+"_1";
      var twoWordK_B1 = "cizu_word_"+i+"_2";
      
      var oneWordK_A2 = "cizu_word_"+i+"_5";
      var twoWordK_B2 = "cizu_word_"+i+"_6";

      _spellTplCommonAdapter(oneWordInfo, oneWordK_A1);
      _spellTplCommonAdapter(twoWordInfo, twoWordK_B1);

      _spellTplCommonAdapter(oneWordInfo, oneWordK_A2);
      _spellTplCommonAdapter(twoWordInfo, twoWordK_B2);
      
      //清除某片区域
      oneWordK_A1 = "cizu_word_"+i+"_3";
      twoWordK_B1 = "cizu_word_"+i+"_4";
            
      oneWordK_A2 = "cizu_word_"+i+"_7";
      twoWordK_B2 = "cizu_word_"+i+"_8";
      _clearTplCommonAdapter(oneWordK_A1);
      _clearTplCommonAdapter(twoWordK_B1);

      _clearTplCommonAdapter(oneWordK_A2);
      _clearTplCommonAdapter(twoWordK_B2);
      

        //画下面对比字词区
        makeCompareTplWordListArea();

      //再写拼音
      oneWordK_A1 = "cizu_pinyin_"+i+"_1";
      twoWordK_B1 = "cizu_pinyin_"+i+"_2";
      
      oneWordK_A2 = "cizu_pinyin_"+i+"_5";
      twoWordK_B2 = "cizu_pinyin_"+i+"_6";

      targetPage.setData({
                           [oneWordK_A1]:oneWordInfo.bishun.pinyin,
                           [twoWordK_B1]:twoWordInfo.bishun.pinyin,
                           [oneWordK_A2]:oneWordInfo.bishun.pinyin,
                           [twoWordK_B2]:twoWordInfo.bishun.pinyin,
                         }
      );
  }
}


function drawTianAndWord(targetPage) {
    var pageWordsList = wordMappingTian.pageWordsList;

    var isUsingOnlineData = false;
    if(arguments.length >= 2){
      isUsingOnlineData = true;
    }

    aCanvasSide = Math.ceil(tianWidth*0.8);//(clientWidth*0.97-clientWidth*0.184)/7}}

    fontSize = aCanvasSide*0.02;
    aBishunCanvasSide = wx.getSystemInfoSync().windowWidth*0.184*0.16;//笔顺画布大小

    tianBmp = new bmpUtil.BitMap();
    tianBmp.createTian();
    targetPage.setData({ tianImg: tianBmp.toBase64() });

    tianWordInfo = [];
    for (var i = 0; i < pageWordsList.length; i++) {
      tianBmp.createTian();
      let oneWord = pageWordsList[i];
      let oneBaseJs;
      if(isUsingOnlineData){
        oneBaseJs = prepareTianDetail.get(oneWord);
      }else{
        oneBaseJs = require('../images/fontData/' + oneWord + '.base');
      }
      var oneBmp = new bmpUtil.BitMap();
      oneBmp.create(oneBaseJs.width, oneBaseJs.height, 0xffffff);
      oneBmp.fromBase64(oneBaseJs.raw);
      console.log(oneWord + ":\twidth=" + oneBmp.width + ",height=" + oneBmp.height);
      var comCombineWord = bmpUtil.combieTwoBitMap(oneBmp, tianBmp, 0xff0000);
      
      tianWordInfo.push({width:oneBmp.width,height:oneBmp.height,bitmap:oneBmp,base64:comCombineWord.toBase64(),timer:-1,wordInfoDesc:oneBaseJs,myWordStrokeIdx:0,myCanvas:null,fontWidth:0,fontHeight:0,leftBanner:wordMappingTian.leftBanner[i],rightBanner:wordMappingTian.rightBanner[i],bottomBanner:wordMappingTian.bottomBanner[i],sentence:wordMappingTian.sentence[i],constitute:wordMappingTian.constitute[i]});
    }

    targetPage.setData({
      tianzige: tianWordInfo,
    },function(){
      setTimeout(function(){
        for (var i = 0; i < pageWordsList.length; i++) {
          _spellBishunWordAdapter(i);//分笔绘画出
        }
      },1);

      setTimeout(function(){
        for (var i = 0; i < pageWordsList.length; i++) {
          initAnimationWord(i);
        }
      },1);

      setTimeout(function(){
        //一共画这么几个格子
        _spellTplAdapter(1);
        _spellTplAdapter(2);
        _spellTplAdapter(4);
        _spellTplAdapter(5);
        
        _clearTplAdapter(3);
        _clearTplAdapter(6);

        //画上面对比字区
        makeCompareTplWordArea();
      },1);
    });
  }

function animationTheWord(wordIdx)
{
  var myWordInfo = oneWordInfo;
  var myInitTimer = tianAndWordTimer;
  var oneWordStrokeIdx = currWordStrokeIdx;

  if(typeof wordIdx != "undefined"){
    myInitTimer = tianWordInfo[wordIdx].timer;
    oneWordStrokeIdx = tianWordInfo[wordIdx].myWordStrokeIdx;
    myWordInfo = tianWordInfo[wordIdx].wordInfoDesc;
  }

  //console.log(" animationTheWord(wordIdx)="+wordIdx+","+currWordStrokeIdx+">= "+myWordInfo.drawcourse.length);

  if(oneWordStrokeIdx >= myWordInfo.drawcourse.length){
    oneWordStrokeIdx = 0;
    clearInterval(myInitTimer);
    //console.log("recall after 1000ms initAnimationWord(wordIdx)="+wordIdx);
    setTimeout(initAnimationWord,3000, wordIdx);
    
    if(typeof wordIdx != "undefined"){
      tianWordInfo[wordIdx].myWordStrokeIdx = 0
    }else{
      currWordStrokeIdx = 0;
    }
    return;
  }

  var offsetLeft = (tianWidth - aCanvasSide)/2+2;

  var onePos = myWordInfo.drawcourse[oneWordStrokeIdx];
  
  var onePosX = offsetLeft+onePos[0]*aCanvasSide;
  var onePosY = offsetLeft+onePos[1]*aCanvasSide;

  var myCanvas = wordACanvas;
  if(typeof wordIdx != "undefined"){
    myCanvas = tianWordInfo[wordIdx].myCanvas; 
  }
  myCanvas.fillRect(onePosX, onePosY, fontSize, fontSize) ;
  myCanvas.draw(true);
  
  if(typeof wordIdx != "undefined"){
    tianWordInfo[wordIdx].myWordStrokeIdx++;
  }else{
    currWordStrokeIdx++;
  }
}

function initAnimationWord(wordIdx)
{
  var myInitTimer = tianAndWordTimer;
  if(typeof wordIdx != "undefined"){
    myInitTimer = tianWordInfo[wordIdx].timer;
  }

  clearInterval(myInitTimer);
  //console.log(tianWordInfo[wordIdx].wordInfoDesc.bishun.bihuaNum);
  // 需要基于浏览器测试
  var myCanvas = wordACanvas;
  if(typeof wordIdx != "undefined"){
    myCanvas = wx.createCanvasContext("tian-bihua-show-per-"+wordIdx);
  }

  //console.log("initAnimationWord(wordIdx)="+wordIdx+"\t  tian-bihua-show-per-"+wordIdx+"\t  aCanvasSide="+aCanvasSide)
  myCanvas.clearRect(0,0,aCanvasSide,aCanvasSide);
  myCanvas.draw();
  myCanvas.setLineWidth(0.8);
  myCanvas.setFillStyle('rgba(0,0,0,0.4)');//

  myInitTimer = setInterval(animationTheWord,10, wordIdx);
  if(typeof wordIdx != "undefined"){
    tianWordInfo[wordIdx].timer = myInitTimer;
    tianWordInfo[wordIdx].myWordStrokeIdx = 0;
    tianWordInfo[wordIdx].myCanvas = myCanvas; 
  }else{
    tianAndWordTimer = myInitTimer;
    currWordStrokeIdx = 0;
  }
}

function getBihuaByStrokes(oneWordInfo)
{
    var bihuaList = [];
    
    var curX = (oneWordInfo.drawcourse[0][0]/100)*aCanvasSide;
    var curY = (oneWordInfo.drawcourse[0][1]/100)*aCanvasSide;

    var oneStrokes = [[curX,curY]];

    
    for(var i=1;i<oneWordInfo.drawcourse.length;i++){
      var onePos = oneWordInfo.drawcourse[i];

      var curX = (onePos[0]/100)*aCanvasSide;
      var curY = (onePos[1]/100)*aCanvasSide;

      var preX = oneStrokes[oneStrokes.length-1][0];
      var preY = oneStrokes[oneStrokes.length-1][1];

      if(Math.abs(curX-preX) > 2 &&
         Math.abs(curY-preY) > 2
      ){
        bihuaList.push(oneStrokes);
        oneStrokes = [];
      }

      oneStrokes.push([curX,curY]);
    }

    if(oneStrokes.length > 0){
      bihuaList.push(oneStrokes);
      oneStrokes = [];
    }

    return bihuaList;
}

function spellBihuaWord()
{
  var bihuaInfo = [];

  var getBihuaList = getBihuaByStrokes(oneWordInfo);
  // 需要基于浏览器测试
   targetPage.setData({
    biHua_info:oneWordInfo.bihua,
  });
}

function spellBishunWord()
{
  //console.log(oneWordInfo.bishun.bishun);
  // 需要基于浏览器测试
   targetPage.setData({
    bishun_info:oneWordInfo.bishun.bishun,
  }, function () {
    　_spellBishunWordAdapter();
  });

}

function _clearTplCommonAdapter(canvasId=String)
{
      var oneBihuaCanvas = wx.createCanvasContext(canvasId);
      oneBihuaCanvas.clearRect(0,0,tianWidth,tianWidth);
      oneBihuaCanvas.draw(false);
}

function _spellTplCommonAdapter(myWordInfo, canvasId=String)
{
      var oneBihuaCanvas = wx.createCanvasContext(canvasId);
      //console.log(key+"\t_spellBishunWordAdapter");
      oneBihuaCanvas.setLineWidth(0.8);
      oneBihuaCanvas.setLineCap('round');
      oneBihuaCanvas.setLineJoin('round');
      oneBihuaCanvas.clearRect(0,0,tianWidth,tianWidth);
      oneBihuaCanvas.setFillStyle("rgba(238,180,180,1)");// 
      //一共循环 N 次
      var offsetLeft = (tianWidth - aCanvasSide)/2+2;
      for(var i=0;i<myWordInfo.drawcourse.length;i++){
          //每个字依次写 ∑(1-n) 次

          var onePos = myWordInfo.drawcourse[i];
          
          var onePosX = offsetLeft+onePos[0]*aCanvasSide;
          var onePosY = offsetLeft+onePos[1]*aCanvasSide;

          oneBihuaCanvas.fillRect(onePosX, onePosY, fontSize, fontSize) ;
      }
      
      oneBihuaCanvas.draw(true);
}

function clearOneTian(canvasId)
{
    if(canvasId.length == 0){
        return;
    }

    //makeCompareTp    l(canvasId);
    console.log("clearOneTian");
    if(wordMappingTian.isNeedDraw(canvasId))
    {
      //var oneWord = wordMappingTian.getOneWordByMappingId(canvasId);
      //if(oneWord.length > 0){
      _drawOneTplByWord(canvasId);
      //}
    }else{
      _clearOneCanvasById(canvasId);
    }
}

function clearAllTian()
{
  var tianHelperPosKey = tianHelper.getAllCanvasKey();
  for(var i=0;i<tianHelperPosKey.length;i++){
    var oneKey = tianHelperPosKey[i];
    clearOneTian(oneKey);
  }

}

function _clearOneCanvasById(key=String)
{
  var oneBihuaCanvas = wx.createCanvasContext(key);
  oneBihuaCanvas.clearRect(0,0,tianWidth,tianWidth);
  oneBihuaCanvas.draw();
}

function _drawNotPaintOneTplById(oneBihuaCanvas, myWordInfo)
{

  oneBihuaCanvas.setLineWidth(1);
  oneBihuaCanvas.setLineCap('round');
  oneBihuaCanvas.setLineJoin('round');
  oneBihuaCanvas.clearRect(0,0,tianWidth,tianWidth);
  oneBihuaCanvas.setFillStyle("rgba(238,180,180,1)");// 
  //一共循环 N 次
  //每个字依次写 n 次
  var offsetLeft = (tianWidth - aCanvasSide)/2+2;
  for(var i=0;i<myWordInfo.drawcourse.length;i++){
      var onePos = myWordInfo.drawcourse[i];
      
      var onePosX = offsetLeft+onePos[0]*aCanvasSide;
      var onePosY = offsetLeft+onePos[1]*aCanvasSide;

      oneBihuaCanvas.fillRect(onePosX, onePosY, fontSize, fontSize) ;
  }
}

function _convertTplCanvasIdToReal(key=String)
{
    var convertId = key.replace(/tpl_/,"");
    return convertId;
}

function _drawOneTplByWord(key=String)
{
  var mappingKey = _convertTplCanvasIdToReal(key);
  var oneWord = wordMappingTian.getOneWordByMappingId(mappingKey);
  var myWordInfo = prepareTianDetail.get(oneWord);
  
  var isOffset = true;
  if(arguments.length == 2){
    isOffset = false;
  }

  var oneBihuaCanvas = wx.createCanvasContext(key);
  oneBihuaCanvas.setLineWidth(1);
  oneBihuaCanvas.setLineCap('round');
  oneBihuaCanvas.setLineJoin('round');
  oneBihuaCanvas.clearRect(0,0,tianWidth,tianWidth);
  oneBihuaCanvas.setFillStyle("rgba(238,180,180,1)");// 
  //一共循环 N 次
  var fontHeight = 0;
  var fontWidth = 0;

  //每个字依次写 n 次
  var offsetLeft = (tianWidth - aCanvasSide)/2+2;
  var thisTimeFontSize = fontSize;
  if(!isOffset){
      offsetLeft = 0;
      thisTimeFontSize *= 1.5;
  }

  //console.log("下面田字格的画="+key);
  for(var i=0;i<myWordInfo.drawcourse.length;i++){
      var onePos = myWordInfo.drawcourse[i];

      var justFontWidth = onePos[0]*aCanvasSide;
      var jsutFontHeight = onePos[1]*aCanvasSide

      var onePosX = offsetLeft+justFontWidth;
      var onePosY = offsetLeft+jsutFontHeight;
      if(fontHeight<jsutFontHeight){
          fontHeight = jsutFontHeight;
      }

      if(fontWidth < justFontWidth){
         fontWidth = justFontWidth;
      }
      oneBihuaCanvas.fillRect(onePosX, onePosY, thisTimeFontSize, thisTimeFontSize) ;
  }

  oneBihuaCanvas.draw(true);
  //console.log(oneWord+" 尺寸: height:"+fontHeight+"\twdith:"+fontWidth);
  myWordInfo.fontHeight = fontHeight;
  myWordInfo.fontWidth = fontWidth;

  prepareTianDetail.set(oneWord, myWordInfo);
}

function _drawOneTplById(key=String, j=Number)
{
  var myWordInfo = tianWordInfo[j].wordInfoDesc;
  
  var isOffset = true;
  var thisTimeFontSize = fontSize;
  if(arguments.length == 3){
    isOffset = false;
    thisTimeFontSize*=1.5;
  }

  var oneBihuaCanvas = wx.createCanvasContext(key);
  oneBihuaCanvas.setLineWidth(1);
  oneBihuaCanvas.setLineCap('round');
  oneBihuaCanvas.setLineJoin('round');
  oneBihuaCanvas.clearRect(0,0,tianWidth,tianWidth);
  oneBihuaCanvas.setFillStyle("rgba(238,180,180,1)");//

  //一共循环 N 次
  var fontHeight = 0;
  var fontWidth = 0;

/*
  var xxc;
  if(key=='tian-bihua-show-tpl-1-0')
  {
    console.log(key);
    xxc = wx.createCanvasContext("tian-bihua-show-tpl-7-0");
  //console.log(key+"\t_spellBishunWordAdapter");
    xxc.setLineWidth(fontSize);
    xxc.clearRect(0,0,tianWidth,tianWidth);
    xxc.setFillStyle("blue");// 
  }
*/
  //每个字依次写 n 次
  var offsetLeft = (tianWidth - aCanvasSide)/2+2;
  if(!isOffset){
      offsetLeft = 0;
  }

  //console.log("上面田字格的画"+key);
  var thisTimeFontS = thisTimeFontSize;
  if(myWordInfo.bishun.bihuaNum < 8 &&
    !isOffset
  ){
    thisTimeFontS+=1;
  }
  for(var i=0;i<myWordInfo.drawcourse.length;i++){
      var onePos = myWordInfo.drawcourse[i];

      var justFontWidth = onePos[0]*aCanvasSide;
      var jsutFontHeight = onePos[1]*aCanvasSide

      var onePosX = offsetLeft+justFontWidth;
      var onePosY = offsetLeft+jsutFontHeight;
      if(fontHeight<jsutFontHeight){
          fontHeight = jsutFontHeight;
      }

      if(fontWidth < justFontWidth){
         fontWidth = justFontWidth;
      }
      oneBihuaCanvas.fillRect(onePosX, onePosY, thisTimeFontS, thisTimeFontS) ;
  }

  /*
  if(key=='tian-bihua-show-tpl-1-0')
  {
    xxc.draw(true);
  }
  */

  oneBihuaCanvas.draw(true);
  //console.log("设置每个字体的尺寸("+key+")\theight:"+fontHeight+"\twidth:"+fontWidth)
  tianWordInfo[j].fontHeight = fontHeight;
  tianWordInfo[j].fontWidth = fontWidth;
}

function makeCompareTplWordArea()
{
  var keyPrefix = 'tian-bihua-show-tpl-7-';

  for(var j=0;j<tianWordInfo.length;j++){
      var key = keyPrefix+j;
      _drawOneTplById(key, j, false);
  }
}

function _getTplNameByWordListCanvasId(oneCanvsId=String)
{
    var key = "";
    //写字的id转换为对比模板id
    //cizu_word_tpl_0_1
    var matchInfo = oneCanvsId.match(/cizu_word_(\d+)_(\d+)/i);
    if(matchInfo != null){
        var rowNum =  matchInfo[1];
        var columnNum = matchInfo[2];

        var targetCol = 1;
        if(columnNum%2 == 0)
        {
            targetCol = 2;
        }

        key = 'cizu_word_tpl_'+rowNum+'_'+targetCol;
        console.log("清楚对比模板 id="+key);
    }

    return key;
  }

function makeOneWordListByCanvasId(canvasId=String)
{
    //写字的id转换为对比模板id
    //cizu_word_tpl_0_1
    var matchInfo = canvasId.match(/cizu_word_(\d+)_(\d+)/i);
    if(matchInfo != null){
        var rowNum =  matchInfo[1];
        var columnNum = matchInfo[2];

        var targetCol = 1;
        if(columnNum%2 == 0)
        {
            targetCol = 2;
        }

        var key = 'cizu_word_tpl_'+rowNum+'_'+targetCol;
        _drawOneTplByWord(key, false);
        console.log("清楚对比模板 id="+key);
    }

    
}

function makeCompareTplWordListArea()
{
  //[0-2]_[1-2]
  for(var i=0;i<wordMappingTian.wordPhraseList.length;i++){
    for(var j=1;j<=wordMappingTian.wordPhraseList[i].length;j++){
        var key = 'cizu_word_tpl_'+i+'_'+j;
        _drawOneTplByWord(key, false);
    }
  }
}


function _clearOneTplById(key=String, j=Number)
{
  var oneBihuaCanvas = wx.createCanvasContext(key);
  oneBihuaCanvas.clearRect(0,0,tianWidth,tianWidth);
  oneBihuaCanvas.draw(false); 
}

function _clearTplAdapter(lineIdx)
{
  var keyPrefix = "tian-bihua-show-";
  if(typeof lineIdx != "undefined"){
    keyPrefix = 'tian-bihua-show-tpl-'+lineIdx+'-';
  }

  for(var j=0;j<tianWordInfo.length;j++){
      var key = keyPrefix+j;
      _clearOneTplById(key, j);
  }
 }

function _spellTplAdapter(lineIdx)
{
  var keyPrefix = "tian-bihua-show-";
  if(typeof lineIdx != "undefined"){
    keyPrefix = 'tian-bihua-show-tpl-'+lineIdx+'-';
  }

  for(var j=0;j<tianWordInfo.length;j++){
      var key = keyPrefix+j;
      _drawOneTplById(key, j);
  }
 }

function _spellBishunWordAdapter(wordIdx)
{
  var myWordInfo = oneWordInfo;
  var keyPrefix = "tian-bihua-show-";
  if(typeof wordIdx != "undefined"){
    //tian-bihua-show-stepbystep-{{index}}-{{bihuaItem.idx}}
    keyPrefix = 'tian-bihua-show-stepbystep-'+wordIdx+'-';
    myWordInfo = tianWordInfo[wordIdx].wordInfoDesc;
  }

  //一共循环 N 次
  for(var i=0;i<myWordInfo.bishun.bishun.length;i++){
    var key = keyPrefix+myWordInfo.bishun.bishun[i].idx;
    var oneBihuaCanvas = wx.createCanvasContext(key);
    //console.log(key+"\t_spellBishunWordAdapter");
    oneBihuaCanvas.setLineWidth(0.5);
    oneBihuaCanvas.setLineCap('round');
    oneBihuaCanvas.setLineJoin('round');
    oneBihuaCanvas.clearRect(0,0,aBishunCanvasSide,aBishunCanvasSide);

    /*太小，看不清，注释了吧。。*/
    /*
    oneBihuaCanvas.setFontSize(8);
    oneBihuaCanvas.setFillStyle("#88A87F");
    oneBihuaCanvas.fillText(myWordInfo.bishun.bishun[i].idx,1,8,5);
    */
    oneBihuaCanvas.draw();

      //每个字依次写 ∑(1-n) 次
      oneBihuaCanvas.setStrokeStyle("rgba(136,168,127,1)");
      for(var innerLoop=0;innerLoop<i;innerLoop++){
        _spellBishunWordAdapterdrawBiShun(myWordInfo, innerLoop, oneBihuaCanvas,aBishunCanvasSide);
      }
      //最后一笔是红色的
      oneBihuaCanvas.setStrokeStyle('red');
      _spellBishunWordAdapterdrawBiShun(myWordInfo, innerLoop, oneBihuaCanvas,aBishunCanvasSide);
  
      oneBihuaCanvas.draw(true);
    }
}

function _spellBishunWordAdapterdrawBiShun(oneWordInfo, innerLoop, oneBihuaCanvas, canvasSide)
{
  var lastLJ = {x:-1,y:-1};

  for(var j = 0;j<oneWordInfo.bishun.bishun[innerLoop].linejoin.length;j++)
  {
    var curX = oneWordInfo.bishun.bishun[innerLoop].linejoin[j].x * canvasSide ; //因为太小
    var curY = oneWordInfo.bishun.bishun[innerLoop].linejoin[j].y * canvasSide;  //所以注释
    //console.log("aCanvasSide:"+canvasSide);

    curX *= 0.6;
    curY *= 0.6;

    curX += canvasSide*0.2;
    curY += canvasSide*0.2;

    if(lastLJ.x != -1 &&
         lastLJ.y != -1  
    ){ 
        var mx = (lastLJ.x + curX)/2;
        var my = (lastLJ.y + curY)/2;

        oneBihuaCanvas.beginPath();
        oneBihuaCanvas.moveTo(lastLJ.x, lastLJ.y);
        oneBihuaCanvas.lineTo(curX, curY);
        //oneBihuaCanvas.quadraticCurveTo(mx+5,my+5,curX+5, curY+5);
        oneBihuaCanvas.stroke();
      }
      
      curX = curX;
      curY = curY;
      lastLJ = {x:curX,y:curY};
  }
}
/*
function animationCurrentWord(oneWord=String,tp)
{
  targetPage = tp;

  wordACanvas = wx.createCanvasContext("tian-bihua-show");
  oneWordInfo = require('../images/fontData/' + oneWord + '.base');

  targetPage.setData({
    animationCanvasSide: aCanvasSide,
    pinyin:oneWordInfo.pinyin,
    bushou:oneWordInfo.bushou,
    duyin:oneWordInfo.duyin,
    bihuashu:oneWordInfo.bishun.bihuaNum,
  },function(){
    initAnimationWord();
    //spellBihuaWord();
    spellBishunWord();
    dupinyin(oneWordInfo.duyin);
  });
}
*/
function ding(){
  var audioFilePath = "/images/fontData/duyin/ding.mp3"
  var res = wx.getSystemInfoSync();
  var audio;
    if (res.platform == 'ios') {
      audio = wx.getBackgroundAudioManager()
    } else {
      audio = wx.createInnerAudioContext();
    }

    audio.title = "叮";
    audio.src = audioFilePath;
    audio.play();
}

function dupinyin(pinyin){
  var audioFilePath = "/images/fontData/duyin/"+pinyin+".ogg"
  var res = wx.getSystemInfoSync();
  var audio;
    if (res.platform == 'ios') {
      audio = wx.getBackgroundAudioManager()
    } else {
      audio = wx.createInnerAudioContext();
    }

    if(prepareTianOgg.get(pinyin)){
      audioFilePath = prepareTianOgg.get(pinyin);
    }

    audio.title = "读音";
    audio.src = audioFilePath;
    audio.play();
}

function isFinishCurrentWordByBihua(strokesNum)
{
  if(lastDrawCanvasId.length == 0){
      return false;
  }
  
  //得到当前字
  var oneWord = wordMappingTian.getOneWordByMappingId(lastDrawCanvasId);
  if(oneWord.length < 0){
      return false;
  }

  if(strokesNum >= prepareTianDetail.get(oneWord).bishun.bihuaNum){
      return true;
  }else{
      return false;    
  }
}


function focusDrawUpByCanvasName(oneWordPos, tp, canvasName)
{
  //ding();
  getHandWrite(oneWordPos, tp, true, canvasName, true);
}

function drawUp(oneWordPos, tp)
{
  var isNeedClear = false;
  isNeedClear = isFinishCurrentWordByBihua(oneWordPos.length);
  if(isNeedClear){
    ding();
  }

  getHandWrite(oneWordPos, tp, isNeedClear, lastDrawCanvasId);

  return isNeedClear;
}
function isSetOffsetPos(){
  return tianHelper.isSetOffsetPos();
}
function setOffsetPos(x=Number, y=Number)
{
  tianHelper.setOffsetPos(x,y);
  return ;
}

function getTianNameByPos(x=Number, y=Number)
{
  var name = tianHelper.getPosNameByPos(x,y);
  
  if(name.length > 0){
    lastDrawCanvasId = name;
  }

  return name;
}


function getTianNameByPosTwo(x=Number, y=Number)
{
  var name = tianHelper.getPosNameByPosTwo(x,y);
  
  if(name.length > 0){
    lastDrawCanvasId = name;
  }

  return name;
}


function setTianMapping(mappingName=String)
{
  wordMappingTian = require('../images/fontData/tian-mapping-' + mappingName + '.base');
}

function hideRedPrompt(tp){
  //tp.isAdjustRed = false;
  var firstEnter = wx.getStorageSync('firstEnter')
  if(firstEnter!==true){
    tp.setData({
      cuePraise:true
    })
    wx.setStorage({
      key: 'firstEnter',
      data: true
    })
  }
  tp.setData({
    "prompt_red_display":"none",
  });

  
  tp.downloadTraceFile();
  
}

function showRedOKPrompt(tp, tempFilePath){
  tp.setData({"prompt_red_file": tempFilePath
            });

  drawAllToCanvas(tp);

  setTimeout(function(){
    hideRedPrompt(tp);
  }, 2000);
  
}

function showRedPrompt(tp, tempFilePath)
{
  pageThis = tp;
  //tp.isAdjustRed = true;
  // tp.setData({"prompt_red_file": tempFilePath,
  //              "prompt_red_display":"block",
  //             "tian_prepare_display":"",
  //             "prompt_red_image_display":"",
  // });
}

function drawAllToCanvas(tp)
{
   for(var i=0;i<tianWordInfo.length;i++){
      clearInterval(tianWordInfo[i].timer);
   }

   tp.setData({
    "tian_draw_info":"(初始化文字)",
    });
   drawTianAndWord(tp, true);

   tp.setData({
    "tian_draw_info":"(初始化词组)",
   });

   drawPhraseAndWord(tp, true);
   tp.setData({
    "tian_draw_icon":"success",
    "tian_draw_info":"(已完成开始对点)",
  });
/*
  if(promptRedSlashTmpPath.length > 0){
    ding();
    showRedPrompt(tp, promptRedSlashTmpPath);
  }*/

}

function pcTestCousrFromFirst(tp){
    isTestCourse = true;
    showRedPrompt(tp, getPromptCameraOrTmpPath());
    prepareTianFile(6, 2);
}

function PcTestCourse(tp){
    drawAllToCanvas(tp);
    setOffsetPos(0,0);
    showRedOKPrompt(tp, getPromptRedOKTmpPath());
}

function pretianTianOggFile(tp, finishOggNum)
{
    //prepareTianOgg
    //tian_ogg_info
    var oneWord = wordMappingTian.pageWordsList.substr(finishOggNum,1);
    var duyin = prepareTianDetail.get(oneWord).duyin;
    var url = "https://wx.ndmooc.com/files/fontdata/word/duyin/"+duyin+".ogg";

    var prompt = "("+duyin+".ogg)";
    
    tp.setData({
      "tian_ogg_info":prompt,
    });

    if(prepareTianOgg.get(duyin)){
      console.log(oneWord+":pretianTianOggFile:"+duyin);
      finishOggNum++;
      if(finishOggNum < wordMappingTian.pageWordsList.length){
        pretianTianOggFile(tp, finishOggNum);
      }else{
        tp.setData({
          "tian_ogg_icon":"success",
          "tian_draw_icon":"download",
        });

        //drawAllToCanvas(tp);
        //ding();        
        //console.log("isAdustPointAlready");

        if(promptRedSlashTmpPath.length > 0 &&
          !isAdustPointAlready
        ){
          showRedPrompt(tp, promptRedSlashTmpPath);
        }else{
          showRedOKPrompt(tp, getPromptRedOKTmpPath());
        }
        
      }
        return;
    }

    console.log(url);
    var totalNumOgg = wordMappingTian.pageWordsList.length;
    wx.downloadFile({
      url: url, //仅为示例，并非真实的资源
        success: (res) => {
          console.log("临时提示文件地址："+res.tempFilePath);
          
          finishOggNum++;
          if(res.statusCode == 200){
            var prompt = "("+finishOggNum+"/"+totalNumOgg+")";
            tp.setData({
                      "tian_ogg_title":prompt,
            });

            prepareTianOgg.set(duyin, res.tempFilePath);
            
            if(finishOggNum < wordMappingTian.pageWordsList.length){
                pretianTianOggFile(tp, finishOggNum);
            }else{
              tp.setData({
                "tian_ogg_icon":"success",
                "tian_draw_icon":"download",
              });

              //====测试过程调用==========================
              if(isTestCourse){
                return PcTestCourse(tp);
              }

              ding();        
              console.log("isAdustPointAlready");
      
              if(promptRedSlashTmpPath.length > 0 &&
                !isAdustPointAlready
              ){
                showRedPrompt(tp, promptRedSlashTmpPath);
              }else{
                showRedOKPrompt(tp, getPromptRedOKTmpPath());
              }
            }
          }else{
            tp.setData({
              "tian_ogg_icon":"warn",
            });
      
            setTimeout(function(){
                  tp.setData({
                    "prompt_red_display":"",
                  });
            }, 3000);
      
            wx.showToast({
                  title: '下载读音文件错误。请检查网络后重试',
                  icon: 'none',
                  duration: 3000
            });
          }
        },
        fail:(es)=>{
          tp.setData({
            "tian_ogg_icon":"warn",
          });
    
          setTimeout(function(){
                tp.setData({
                  "prompt_red_display":"",
                });
          }, 3000);
    
          wx.showToast({
                title: '下载读音文件错误。请检查网络后重试',
                icon: 'none',
                duration: 3000
          });
        }
   });
}

function prepareTianDetailInfo(tp, finishDetailNum)
{
    var totalNum = wordMappingTian.wordPhraseList.length*wordMappingTian.wordPhraseList[0].length;
    
          var i = Math.floor(finishDetailNum / wordMappingTian.wordPhraseList[0].length);
          var j = Math.floor(finishDetailNum % 2);

          var oneWord = wordMappingTian.wordPhraseList[i].substr(j,1);
          var url = "https://wx.ndmooc.com/files/fontdata/word/"+oneWord+".online.js";
          var wordPrompt = "("+oneWord+")";
          tp.setData({
            "cur_tian_detail_word":wordPrompt,
          });

          if(prepareTianDetail.get(oneWord)){
                    console.log("prepareTianDetailInfo 本地有数据");

                    finishDetailNum++;
                    var prompt = "("+finishDetailNum+"/"+totalNum+")";
                    tp.setData({
                              "tian_detail_info":prompt,
                    });
                    
                    if(finishDetailNum >= totalNum){
                        tp.setData({
                          "tian_detail_icon":"success",
                          "tian_ogg_icon":"download",
                          "cur_tian_detail_word":"",
                        });

                        pretianTianOggFile(tp, 0);
                        console.log(prepareTianDetail);
                    }else{
                      prepareTianDetailInfo(tp, finishDetailNum);
                    }

                    return;
          }

          console.log("下载："+url);
          wx.request({
            url: url,
            success (res) {
                  if(res.statusCode == 200){
                    prepareTianDetail.set(oneWord, res.data);

                    finishDetailNum++;
                    var prompt = "("+finishDetailNum+"/"+totalNum+")";
                    tp.setData({
                              "tian_detail_info":prompt,
                    });
                    
                    
                    if(finishDetailNum >= totalNum){
                        tp.setData({
                          "tian_detail_icon":"success",
                          "tian_ogg_icon":"download",
                          "cur_tian_detail_word":"",
                        });

                        pretianTianOggFile(tp, 0);
                        console.log(prepareTianDetail);
                    }else{
                      prepareTianDetailInfo(tp, finishDetailNum);
                    }
                  }else{
                    tp.setData({
                      "tian_detail_icon":"warn",
                      });
              
                      setTimeout(function(){
                          tp.setData({
                            "prompt_red_display":"",
                          });
                      }, 3000);
              
                        wx.showToast({
                          title: '下载详细数据包错误。请检查网络后重试',
                          icon: 'none',
                          duration: 3000
                        });
                  }
            }
          });
    /*
      }
    }*/
}

function prepareAllInfo(classInfo=Number, termNo=Number,pageNo=Number, tp)
{
  console.log("prepareAllInfo");
  var url = "https://wx.ndmooc.com/files/fontdata/mapping/tian-mapping-"+classInfo+"-"+termNo+"-"+pageNo+".base.js";

  tp.setData({
                "tian_package_icon":"download",
             });

  if(prepareWordMappingTian.get(url)){
    console.log("prepareAllInfo 本地已有数据");
    //如果已经下载
    wordMappingTian = prepareWordMappingTian.get(url);
    wordMappingTian.getWordIdByMappingId = getWordIdByMappingId;
    wordMappingTian.isNeedDraw = isNeedDraw;
    wordMappingTian.getOneWordByMappingId = getOneWordByMappingId;
    //接下来读详细信息
    prepareTianDetailInfo(tp,0);  
    return;
  }

  wx.request({
            url: url,
            success (res) {
                  if(res.statusCode == 200){
                    tp.setData({
                      "tian_package_icon":"success",
                      "tian_detail_icon":"download",
                    });
                    
                    prepareWordMappingTian.set(url, res.data);
                    wordMappingTian = res.data;
                    wordMappingTian.getWordIdByMappingId = getWordIdByMappingId;
                    wordMappingTian.isNeedDraw = isNeedDraw;
                    wordMappingTian.getOneWordByMappingId = getOneWordByMappingId;

                    //接下来读详细信息
                    prepareTianDetailInfo(tp,0);
                  }else{
                    tp.setData({
                      "tian_package_icon":"warn",
                      });
              
                      setTimeout(function(){
                          tp.setData({
                            "prompt_red_display":"",
                          });
                      }, 3000);
              
                        wx.showToast({
                          title: '数据未录入',
                          icon: 'none',
                          duration: 3000
                        });
                  }
            }
  });

/*            
  wx.downloadFile({
    url: url, //仅为示例，并非真实的资源
      success: (res) => {
        if(res.statusCode == 200){
          console.log("临时提示文件地址："+res.tempFilePath);
          
        }else{
          tp.setData({
            "tian_package_icon":"warn",
         });

         setTimeout(function(){
            tp.setData({
              "prompt_red_display":"",
            });
         }, 3000);

          wx.showToast({
            title: '下载数据包错误。请检查网络后重试',
            icon: 'none',
            duration: 3000
          })
        }
      }
  });
  */
}

function prepareTianFileByTerm(classInfo=Number, termNo=Number,pageNo=Number)
{
  var tp = pageThis;
  isAdustPointAlready = false;
  if(arguments.length == 4){
    isAdustPointAlready = arguments[3];
  }
  // wx.showToast({
  //   title: classInfo+'年字帖'+pageNo+'页',
  //   icon: 'success',
  //   duration: 3000
  // });

  tp.setData({
              "prompt_red_display":"block",
              "prompt_red_image_display":"none",
              "tian_prepare_display":"block",
              "tian_package_icon": 'circle',
              "tian_detail_icon":'circle',
              "tian_ogg_icon":'circle',
              "tian_draw_info":'',
              "tian_draw_icon":'circle',
              "classInfo":classInfo,
              "pageNum":pageNo,
            });

  prepareAllInfo(classInfo,termNo,pageNo, tp);
}

function prepareTianFile(classInfo=Number, pageNo=Number)
{
  var tp = pageThis;
  isAdustPointAlready = false;
  if(arguments.length == 3){
    isAdustPointAlready = arguments[2];
  }
  // wx.showToast({
  //   title: classInfo+'年字帖'+pageNo+'页',
  //   icon: 'success',
  //   duration: 3000
  // });

  tp.setData({
              "prompt_red_display":"block",
              "prompt_red_image_display":"none",
              "tian_prepare_display":"block",
              "tian_package_icon": 'circle',
              "tian_detail_icon":'circle',
              "tian_ogg_icon":'circle',
              "tian_draw_info":'',
              "tian_draw_icon":'circle',
              "classInfo":classInfo,
              "pageNum":pageNo,
            });

  prepareAllInfo(classInfo,2, pageNo, tp);
}

function clearAllDraw()
{
  var myCanvas = wx.createCanvasContext("partyCanvas");
  myCanvas.clearRect(0,0,app.globalData.clientWidth,app.globalData.clientHeight);
  myCanvas.draw(false);

  if(typeof wordMappingTian.pageWordsList == "undefined"){
    return;
  }

  _clearTplAdapter(3);
  _clearTplAdapter(6);
  //for(var i=1;i<7;i++){
      //_clearTplAdapter(3);
  //}

  for(var i=0;i<wordMappingTian.pageWordsList.length;i++){
     //清除某片区域
     var oneWordK_A1 = "cizu_word_"+i+"_3";
     var twoWordK_B1 = "cizu_word_"+i+"_4";
           
     var oneWordK_A2 = "cizu_word_"+i+"_7";
     var twoWordK_B2 = "cizu_word_"+i+"_8";

     _clearTplCommonAdapter(oneWordK_A1);
     _clearTplCommonAdapter(twoWordK_B1);

     _clearTplCommonAdapter(oneWordK_A2);
     _clearTplCommonAdapter(twoWordK_B2);
  }
}

function getOneWordByMappingId(canvasId=String)
{
  var oneWord = this.getMapping[canvasId].word;

  return oneWord;
}

function getWordIdByMappingId(oneId=String)
{
  var oneWord = this.getMapping[oneId].word;
  var onePosIdx = this.pageWordsList.indexOf(oneWord);

  return onePosIdx;
}

function isNeedDraw(oneId=String)
{
    return this.getMapping[oneId].isShowWord;  
}

function preparePromoptPhoho(){
  wx.downloadFile({
    url: "https://wx.ndmooc.com/files/fontdata/example_red.gif", //仅为示例，并非真实的资源
      success: (res) => {
        console.log("临时提示文件地址："+res.tempFilePath);
        promptRedSlashTmpPath = res.tempFilePath;
      },
      fail:(es)=>{
        wx.showToast({
          title: '下载提示文件错误。请检查网络后重试',
          icon: 'fail',
          duration: 5000
        })
      }
 });

 wx.downloadFile({
  url: "https://wx.ndmooc.com/files/fontdata/example_red_ok.gif", //仅为示例，并非真实的资源
    success: (res) => {
      console.log("临时提示成功地址："+res.tempFilePath);
      promptRedOKTmpPath = res.tempFilePath;
      
    },
    fail:(es)=>{
      wx.showToast({
        title: '下载提示文件成功错误。请检查网络后重试',
        icon: 'fail',
        duration: 5000
      })
    }
  });

  wx.downloadFile({
    url: "https://wx.ndmooc.com/files/fontdata/example_camera_or.gif", //仅为示例，并非真实的资源
      success: (res) => {
        console.log("临时提示拍照地址："+res.tempFilePath);
        promptCameraOrTmpPath = res.tempFilePath;
      },
      fail:(es)=>{
        wx.showToast({
          title: '下载提示文件拍照错误。请检查网络后重试',
          icon: 'fail',
          duration: 5000
        })
      }
  });

}

function getPromptRedSlashTmpPath(){
  return promptRedSlashTmpPath;
}

function getPromptRedOKTmpPath(){
  return promptRedOKTmpPath;
}

function getPromptCameraOrTmpPath(){
  return promptCameraOrTmpPath;  
}//拍照

function getOffsetPoxByXY(x=Number,y=Number)
{
  return tianHelper.getOffsetPoxByXY(x,y);
}

function setOffsetPosTwo(posTwo=Array)
{
  return tianHelper.setOffsetPosTwo(posTwo);
}

function isSetOffsetPosTwo()
{
  return tianHelper.isSetOffsetPosTwo();
}

// 点赞
function giveLike(e)
{
  var tp = pageThis;
  var _this = this;  
  console.log(tp)
  clearTimeout(tp.data.timers)
  tp.setData({
    "like_left":e.offsetLeft+'px',
    "like_top":e.offsetTop+'px',
    'zanZindex':9,
    'zanOpacity':1
  })
  var animation = wx.createAnimation({  
    duration: 1000,  
  })  
  var smallanimation = wx.createAnimation({  
    duration: 1000,  
  })  
  animation.opacity(0).scale(3, 3).step();//修改透明度,放大 
  smallanimation.opacity(0).scale(1.2, 1.2).step().scale(1, 1).step();//修改透明度,放大 
  tp.setData({
    'spreakingAnimation': animation.export(), 
    'smallAnimation':smallanimation.export(),
    'timers':setTimeout(function(){
      tp.setData({
        'zanZindex':0,
        'zanOpacity':0
      })
    },1100) 
  });  
}

module.exports = {
  drawTianAndWord,
  drawPhraseAndWord,
  //animationCurrentWord,
  dupinyin,
  getHandWrite,
  //combieTwoMat,
  combineAndScore,
  Point2d,
  StrokesStore,
  isFinishCurrentWordByBihua,
  //scoreTheWord,
  //justCombine,
  drawUp,
  ding,
  initAnimationWord,
  getTianNameByPos,
  setOffsetPos,
  setTianMapping,
  clearOneTian,
  focusDrawUpByCanvasName,
  showRedPrompt,
  hideRedPrompt,
  showRedOKPrompt,
  prepareTianFile,
  prepareAllInfo,
  getPromptRedSlashTmpPath,//提示圈圈
  getPromptRedOKTmpPath,
  getPromptCameraOrTmpPath,//拍照
  preparePromoptPhoho,
  isSetOffsetPos,
  getOffsetPoxByXY,
  pcTestCousrFromFirst,
  setOffsetPosTwo,
  isSetOffsetPosTwo,
  getTianNameByPosTwo,
  clearAllDraw,
  prepareTianFileByTerm,
  giveLike,
  clearAllTian
};